package cn.tedu.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

//模拟工作队列模式中的生产者
public class WorkProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂对象
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("192.168.8.100");
        cf.setPort(5672);   //默认端口号，可以省略不写
        cf.setUsername("test");
        cf.setPassword("test");
        cf.setVirtualHost("/");  //如果不指定虚拟主机，默认是"/",可以省略不写
        //2.通过连接工厂对象创建tcp连接对象，通过tcp连接对象创建channel
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        //3.通过channel创建队列
        cc.queueDeclare("work.queue", true, false, false, null);
        //4.生产者准备数据---在控制台中输入
        while (true) {
            String msg = new Scanner(System.in).nextLine();
            if (msg.equals("quit")) {
                //5.关闭连接
                nc.close();
            }
            cc.basicPublish("", "work.queue", MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes(StandardCharsets.UTF_8));
        }
    }
}
